from xiaowupkg import *
from tkinter import *
from tkinter import ttk
import pyautogui as pagui
import pyperclip
from PIL import Image, ImageTk
# import wxauto as wx
import time
import os
from openpyxl import load_workbook
import datetime
import sys
if(sys.version[:1] == "3"):
    import _thread as thread
else:
    import thread 

contact = ''
clients = []

class AutoWxGui(object):
    def __init__(self, mine = '文件传输助手'):
        self.mine = mine
        for tt in pagui.getWindowsWithTitle('微信'):
            if tt.title == '微信':
                self.wxwin = tt  
        self.width, self.height = pagui.size()
        self.midwid = (self.width-self.wxwin.width)/2
        self.midhei = (self.height-self.wxwin.height)/2
        print(self.wxwin)
        print("屏幕分辨率：",self.width, self.height)
        print("屏幕中心点:",self.midwid, self.midhei)

    def getWxPath(self):
        if os.path.exists('wechat_path.txt'):
            with open('wechat_path.txt', 'r') as f:
                wxpath = f.read()
                print(wxpath)
        else:
            root_dir = 'C:\\'  # 从根目录开始搜索，可以根据需要更改
            wechat_paths = []
            # 遍历文件系统 路径,文件夹名字,文件名
            for root, dirs, files in os.walk(root_dir):
                # print(root, dirs, files)
                for file in files:
                    if file.lower() == 'wechat.exe':
                        wechat_paths.append(os.path.join(root, file))
            # 打印找到的微信路径
            for wechat_path in wechat_paths:
                print(wechat_path)
            wxpath = '"' + wechat_paths[0].replace('\\', '/') + '"'
            with open('wechat_path.txt', 'w', encoding='utf-8') as f:
                f.write(''.join(wxpath))
        return wxpath

    def open_wechat(self):
        wxpath = self.getWxPath()
        pagui.hotkey('win', 'r')
        pagui.typewrite('cmd')
        pagui.press('enter')
        pagui.press('enter')
        time.sleep(1)
        self.typewrite(wxpath)
        pagui.press('enter')
        time.sleep(1)  # 等待微信应用程序打开
        pagui.moveTo(self.wxwin.left + 10, self.wxwin.top + 10)
        pagui.dragTo(self.midwid, self.midhei,duration=0.5)
        self.close_app("C:\\")
    
    def close_app(self, name):
        app = pagui.getWindowsWithTitle(name)[0]
        print('close ', app)
        pagui.click(app.left + 10, app.top + 10)
        time.sleep(0.5)
        pagui.hotkey('alt', 'f4')
        time.sleep(0.5)
        pagui.click(self.midwid+10, self.midhei+10)
        time.sleep(0.5)

    def typewrite(self, text):
        pyperclip.copy(text)
        pagui.keyDown('ctrl')
        pagui.press('v')
        pagui.keyUp('ctrl')
        # 添加适当的延迟，确保文本输入完全
        time.sleep(0.5)

    def search_chat(self, keyword):
        print('in search_chat')
        pagui.hotkey('ctrl', 'f')
        time.sleep(0.5)
        self.typewrite(keyword)
        pagui.press('enter')
        print('search_chat finished')

    def send_msg(self, msg):
        pagui.hotkey('ctrl', 'a')
        time.sleep(1)
        self.typewrite(msg)
        pagui.press('enter')

    def msg_alarm(self, info):
        self.search_chat(self.mine)
        self.send_msg(info)

def getMsgTimes():
    timelist = [175000, 182000, 185000, 192000, 195000, 202000, 205000, 212000, 215000, 222000]
    timenow = int(time.strftime('%H%M%S', time.localtime(time.time())))
    if timenow >= 170000:
        for index, item in enumerate(timelist):
            # print(index, item)
            if timenow >= item and timenow <= item + 5:
                return index
    return -1
    # print(timenow)

def readxlsx(path):
    global clients
    # 读取Excel文件
    workbook = load_workbook(path)
    worksheet = workbook['Sheet1']
    
    # 打印数据
    for cols in worksheet.iter_cols(values_only=True):
        coltext = []
        for col in cols:
            if type(col) is not datetime.time and col is not None:
                coltext.append(col)
        clients.append(coltext)
    print(clients)

def moyuFunction():
    #    获取群聊关键字
    readxlsx('file.xlsx')
    info = 'this is a auto send message'
    timenow = int(time.strftime('%H%M%S', time.localtime(time.time())))
    global clients
    print(clients)
    while timenow <= 223000:
        global contact
        timenow = int(time.strftime('%H%M%S', time.localtime(time.time())))
        index = getMsgTimes()
        if index != -1:
            #输出提醒信息
            send_error = []
            wx = AutoWxGui(contact)
            wx.open_wechat()
            for client in clients[index]:
                try:
                    wx.search_chat(client)
                    wx.send_msg(info)
                except Exception as e:
                    # 处理未知类型的异常
                    wx.msg_alarm("发送消息失败", e)
                    send_error.append(client)
            #发送失败错误处理
            while len(send_error) > 0:
                for msg in send_error:
                    try:
                        wx.search_chat(msg)
                        wx.send_msg(info)
                    except Exception as e:
                        # 处理未知类型的异常
                        wx.msg_alarm("重发消息失败", e)
                    else:
                        wx.msg_alarm("重发消息成功")
                        send_error.remove(msg)
        time.sleep(1)
    wx.msg_alarm("今日任务已完成, have a nice day!")

class Page:
    def __init__(self):
        self.root
        self.wid
        self.hei
        self.can
        self.time
        
    def get_img(self):
        self.impath = '1.jpg'
        self.err = 1
        self.btnerr = 1
        try:
            img = Image.open(self.impath).resize((self.wid,self.hei))
            self.im = ImageTk.PhotoImage(img)
        except FileNotFoundError as e:
            print('请在文件目录添加1.jpg的背景图片!')
            self.err = 0
    def gettime(self):
        time = datetime.datetime
        endtime = time.today().strftime('%Y%m%d')
        self.time = endtime

    def setbg(self):
        #设置背景图片
        if self.err == 1:
            self.can = Canvas(self.root, width = self.wid, height = self.hei, bg='white')
            self.can.create_image(self.wid/2,self.hei/2,image = self.im)    #图片中心点位置
            self.can.grid(column=0,row=0)

    def getwinsize(self, root):
        self.screen_width = root.winfo_screenwidth()
        self.screen_height = root.winfo_screenheight()
    
    def win_init(self, title=None, iconimg=None):
        self.get_img()
        self.setbg()
        self.getwinsize(self.root)
        screen_width = (self.screen_width - self.wid)/2
        screen_height = (self.screen_height - self.hei)/2
        try:
            if os.path.splitext(iconimg)[1] == '.png':
                png_image = Image.open(iconimg)
                 # 将图像转换为 ICO 格式
                png_image.save(os.path.splitext(iconimg)[0] + '.ico')
                iconimg = os.path.splitext(iconimg)[0] + '.ico'
           
            self.root.iconbitmap(iconimg)
        except:
            print('icon.ico not found')
        self.root.geometry(f'{self.wid}x{self.hei}+{int(screen_width)}+{int(screen_height)}')
        self.root.resizable(FALSE, FALSE)
        if title is not None:
            self.root.title(title)
        self.root.configure(bg='#BEEDC7')

class MainPage(Page):
    def __init__(self, root, width, height):
        self.root = root
        self.hei = height
        self.wid = width
        self.frm = ''
        self.text = StringVar()
        self.text1 = StringVar()
        self.input = StringVar()
        style = ttk.Style()
        style.configure("D.TLabel", relief=FLAT, foreground='black',anchor='center', font=('幼圆', 22),background= '#949294')
        style.configure("E.TLabel", relief=FLAT, foreground='white',anchor='center', font=('幼圆', 15),background= '#5c5c5c')
        style.configure("F.TLabel", relief=FLAT, foreground='white',anchor='center', font=('幼圆', 13),background= 'black')
        style.configure("B.TLabel", relief=RAISED, foreground='black',anchor='center', font=('幼圆', 13),background= 'white', activebackground = 'red', border = 3)
        style.configure("G.TLabel", relief=FLAT, foreground='white',anchor='center', font=('幼圆', 30),background= '#5c5c5c')
        self.win_init(title='摸鱼小能手', iconimg= 'icon.ico')
        self.creat()

    def creat(self):
        #定义组件
        self.text.set('Nothing for now!\n')
        self.text1.set('显示窗口')
        self.frm2 = ttk.Frame(self.root,style='F.TLabel', padding = (0, 0, 0, 0), width = self.wid, height = self.hei, borderwidth=5)
        self.frm2.place(x = 0, y = 0, height= self.hei, width=self.wid)
        self.frm0 = ttk.Frame(self.root,style='D.TLabel', padding = (0, 0, 0, 0), width = 40, height = self.hei/2, borderwidth=2)
        self.frm0.place(x = 5, y = 5, height= self.hei*0.6, width=40)
        self.frm = ttk.Frame(self.root,style='E.TLabel', padding = (0, 0, 0, 0), width = self.wid, height = self.hei/2, borderwidth=1)
        self.frm.place(x = 50, y = 5, height= self.hei*0.6, width=self.wid - 55)
        self.frm1 = ttk.Frame(self.root,style='E.TLabel', padding = (0, 0, 0, 0), width = self.wid, height = self.hei, borderwidth=5)
        self.frm1.place(x = 5, y = self.hei*0.6+35, height= self.hei*0.4-40, width=self.wid - 10)
        self.frminput = ttk.Frame(self.root,style='G.TLabel', padding = (0, 0, 0, 0), width = self.wid, height = 30, borderwidth=5)
        self.frminput.place(x = 5, y = self.hei*0.6+10, height= 40, width=self.wid - 10)
        

        self.lab = ttk.Label(self.frm0, style = 'D.TLabel', anchor=CENTER, textvariable = self.text1,wraplength = 10, border= 5, borderwidth=2)
        self.lab1 = ttk.Label(self.frm, style = 'E.TLabel', textvariable = self.text, wraplength = self.wid - 55)
        self.but = ttk.Button(self.frm1, style = 'B.TLabel', cursor = 'hand2', width = 6, padding= 2 , text = "开始", command=self.start)
        self.but2 = ttk.Button(self.frm1, style = 'B.TLabel', cursor = 'hand2', width = 6, padding= 2 , text = "结束", command=self.close)
        self.input = ttk.Entry(self.frminput, style = 'G.TLabel',font=('幼圆', 15), width = 28, textvariable=self.input)
        # self.but1 = ttk.Button(self.frm1, style = 'B.TLabel', cursor = 'hand2', text="返回", width= 8, padding= 5  , command=self.returnmain)

        self.lab.pack(pady=80, padx= 0)
        self.lab1.grid(column=1, row=0)
        self.input.grid()
        self.but.grid(column=1,row=1, padx= 10, pady= 10)
        self.but2.grid(column = 2, row=1, padx= 10, pady= 10)
        # self.but1.grid(column = 3, row=0, padx= 10, pady= 10)

        self.input.bind('<FocusIn>', self.on_entry_click)
        self.input.bind('<FocusOut>', self.on_focusout)
        self.input.bind('<Return>', self.start)
        self.on_focusout()

    def on_entry_click(self, event = None):
        self.input.configure(foreground='white')  # 设置文字颜色为灰色
        if self.input.get() == '请输入紧急联系人微信名':
            self.input.delete(0, END)  # 删除提示文字

    def on_focusout(self,event = None):
        if self.input.get() == '':
            self.input.configure(foreground='gray')  # 设置文字颜色为灰色
            self.input.insert(0, '请输入紧急联系人微信名')  # 恢复提示文字

    def start(self, e = None):
        global contact
        if self.input.get() != '请输入紧急联系人微信名':
            print('程序已启动,紧急联系人为:', self.input.get())
            self.text.set(f'程序已启动\n你的紧急联系人已设置为:{self.input.get()}')
            contact = self.input.get()
            thread.start_new_thread(moyuFunction, ())
            
        else:
            print('程序已启动,紧急联系人为: 文件传输助手')
            self.text.set('程序已启动\n你的紧急联系人已设置为: 文件传输助手')
            contact = '文件传输助手'
            thread.start_new_thread(moyuFunction, ())

    def close(self):
        exit(0)

if __name__ == '__main__':
    #创建主窗口实例
    root = Tk()
    MainPage(root, 300, 500)
    root.mainloop()

    # # 创建主窗口
    # root = Tk()
    # root.title("终端效果示例")

    # # 创建滚动条
    # scrollbar = ttk.Scrollbar(root)
    # scrollbar.pack(side=RIGHT, fill=Y)

    # # 创建滑动显示框
    # text_widget = Text(root, yscrollcommand=scrollbar.set)
    # text_widget.pack(side=LEFT, fill=BOTH)

    # # 添加示例文本
    # for i in range(100):
    #     text_widget.insert(END, f"这是第 {i+1} 行\n")

    # # 绑定滚动条和滑动显示框
    # scrollbar.config(command=text_widget.yview)

    # # 运行主循环
    # root.mainloop()


